//
//  AppClient.m
//  Water
//
//  Created by yh on 2017/11/27.
//  Copyright © 2017年 chenguibang. All rights reserved.
//

#import "AppClient.h"
#import "UserInfoModifyRespone.h"
#import "ApiResponse.h"
#import "APIBaseResponse.h"
#import "BaseResponse.h"
#import "UserInfoRespone.h"
#import <UserCenterManager.h>
#import <AudioToolbox/AudioToolbox.h>
#import <MJExtension/MJExtension.h>
#define DEFULT_TARGET @"2000"
#define ENCODE_PATH [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingString:@"/AppClient.data"]
@implementation AppClient
MJCodingImplementation
+ (instancetype)shared{
    static dispatch_once_t onceToken;
    static AppClient *shareInstance = nil;
    dispatch_once(&onceToken, ^{
        AppClient *app = [NSKeyedUnarchiver unarchiveObjectWithFile:ENCODE_PATH];
        if (!app) {
            shareInstance = [[AppClient alloc]init];
            [shareInstance useDefultPlans:YES];
            shareInstance.todayTarget = DEFULT_TARGET;
            shareInstance.currentServer = [[ServerModel alloc] init];
            shareInstance.currentServer.host = @"192.168.31.140";
            shareInstance.currentServer.port = @"8989";
            [NSKeyedArchiver archiveRootObject:shareInstance toFile:ENCODE_PATH];
        }else{
            shareInstance = app;
        }
        
//        shareInstance = [[AppClient alloc]init];
       [[UserCenterManager shared] addObserver:shareInstance forKeyPath:@"currentToken" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
        [[UserCenterManager shared] addObserver:shareInstance forKeyPath:@"rc_token" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
        
    });
    return shareInstance;
}

- (void)addPlan:(PlanItem *)plan{
    if (![self.plans containsObject:plan]) {
            [self.plans addObject:plan];
    }
    [self savePlans];
}

- (void)deletePlan:(PlanItem *)plan{
    if ([self.plans containsObject:plan]) {
        [self.plans removeObject:plan];
    }
    [self savePlans];
}

- (void)updatePlan:(PlanItem *)plan{
    
}

- (void)savePlans{
    [NSKeyedArchiver archiveRootObject:self toFile:ENCODE_PATH];
    [[AppNotificationManager shareManager] refresh];
}

- (void)useDefultPlans:(BOOL)defult{
    [self.plans removeAllObjects];
    
    if(defult){
        [self.plans addObjectsFromArray:self.defultPlans];
    }else{
        
    }
    [self savePlans];
    
}


- (void)addBottle:(BottleItem *)bottle{
    if (![self.customBottles containsObject:bottle]) {
        [self.customBottles addObject:bottle];
    }
    [self saveBottles];
}

- (void)deleteBottle:(BottleItem *)bottle{
    if ([self.customBottles containsObject:bottle]) {
        [self.customBottles removeObject:bottle];
    }
    [self savePlans];
}

- (void)updateBottle:(BottleItem *)bottle{
    
}

- (void)saveBottles{
    [NSKeyedArchiver archiveRootObject:self toFile:ENCODE_PATH];
    [[AppNotificationManager shareManager] refresh];
}




- (NSMutableArray *)customBottles{
    if(!_customBottles){
        _customBottles = [[NSMutableArray alloc]init];
    }
    return _customBottles;
}

- (NSMutableArray *)plans{
    if (!_plans) {
        _plans = [[NSMutableArray alloc]init];
    }
    return _plans;
}


- (NSArray *)defultPlans{
    return @[
             [PlanItem planWithTag:@"起床一杯淡盐水或温度事宜的白开水用以补充夜晚流失的水分，清肠排毒。半小时之后，再用早餐" hour:7 minute:00 second:00 isRemind:YES],
                [PlanItem planWithTag:@"工作：到单位后喝水。清晨的忙碌已经使水分在不知不觉中流失了很多，此时的补水特别重要。" hour:8 minute:30 second:00 isRemind:YES],
                [PlanItem planWithTag:@"午餐：忙了一上午该休息了，用餐前适当喝点水有助于激活消化系统活力，同时要注意喝完后不要立即进餐。" hour:11 minute:30 second:00 isRemind:YES],
                [PlanItem planWithTag:@"休息：午餐半小时后，可以少量喝些水。" hour:12 minute:30 second:00 isRemind:YES],
                [PlanItem planWithTag:@"工作：上班用一杯清茶消除疲劳，这一杯同样也很重要。" hour:14 minute:30 second:00 isRemind:YES],
                [PlanItem planWithTag:@"下班：下班前喝杯水除了补充流失的水分之外，还能给肠胃带来饱胀感，减少晚餐食量，特别适用于想减肥的人士。" hour:17 minute:30 second:00 isRemind:YES],
                [PlanItem planWithTag:@"睡觉：临睡前一至半小时喝一些水，但不宜喝得太多。" hour:22 minute:30 second:00 isRemind:YES],
              
             ];
}



- (NSMutableArray<ServerModel *> *)servers{
    if (!_servers) {
        _servers = [[NSMutableArray alloc]init];
    }
    return _servers;
}


- (void)setTodayTarget:(NSString *)todayTarget{
    _todayTarget = todayTarget;
    [self savePlans];
}

+ (NSArray *)mj_allowedCodingPropertyNames{
    return @[@"plans",@"todayTarget",@"servers",@"currentServer",@"customBottles"];
}


- (void)dealloc{
//    [[UserCenterManager shared] removeObserver:self forKeyPath:@"currentToken"];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    if([keyPath isEqualToString:@"currentToken"]){
        [[UserCenterManager shared] getCurrentUserInfoWith:^(UserInfo *userInfo) {
            
        }];
    }
    if([keyPath isEqualToString:@"rc_token"]){
        
        
        if([UserCenterManager shared].rc_token.length > 0){
             [self rc_login];
        }else{
            [self rc_logout];
        }
    }
    
}

- (void)setup{
    [[RCIM sharedRCIM] initWithAppKey:@"k51hidwqknmlb"];
//    [[RCIMClient sharedRCIMClient] initWithAppKey:@"k51hidwqknmlb"];
    [[RCIM sharedRCIM] setUserInfoDataSource:self];
    [[RCIM sharedRCIM] setGroupInfoDataSource:self];
    [[RCIM sharedRCIM] setReceiveMessageDelegate:self];
    [self rc_login];
}


- (void)rc_login{
    if([UserCenterManager shared].rc_token.length > 0){
        
        [[RCIMClient sharedRCIMClient] connectWithToken:[UserCenterManager shared].rc_token success:^(NSString *userId) {
            NSLog(@"登陆成功。当前登录的用户ID：%@", userId);
            
            
//            [[RCIMClient sharedRCIMClient] setDiscussionInviteStatus:@"3e7a4de9-b348-49a3-aa55-d36f6ae1ce01" isOpen:YES success:^{
//
//            } error:^(RCErrorCode status) {
//
//            }];
//
//            [[RCIMClient sharedRCIMClient] addMemberToDiscussion:@"3e7a4de9-b348-49a3-aa55-d36f6ae1ce01" userIdList:@[userId] success:^(RCDiscussion *discussion) {
//
//            } error:^(RCErrorCode status) {
//
//            }];
            
        } error:^(RCConnectErrorCode status) {
             NSLog(@"登陆的错误码为:%d", status);
        } tokenIncorrect:^{
            
        }];
        
        
    }
}

- (void)rc_logout{
    
    [[RCIMClient sharedRCIMClient] logout];
}


- (void)getUserInfoWithUserId:(NSString *)userId completion:(void (^)(RCUserInfo *))completion{
    [[UserCenterManager shared] getUserInfoWithUserId:userId reuslt:^(UserInfo *userInfo) {
        RCUserInfo *rcUser = [[RCUserInfo alloc]initWithUserId:userId name:userInfo.nickname portrait:userInfo.avatar];
        completion(rcUser);
    }];
}
- (void)getGroupInfoWithGroupId:(NSString *)groupId
                     completion:(void (^)(RCGroup *groupInfo))completion{
    
}


- (void)onRCIMReceiveMessage:(RCMessage *)message
                        left:(int)left{
    
    
    
    
    if ([message.objectName isEqualToString:@"RC:CmdMsg"]) {
        dispatch_async(dispatch_get_main_queue(), ^{
            
            
            CAKeyframeAnimation *popAnimation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
            popAnimation.duration = 0.4;
            popAnimation.values = @[[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0f, 1.0f, 1.0f)],
                                    [NSValue valueWithCATransform3D:CATransform3DMakeScale(1.1f, 1.1f, 1.0f)],
                                    [NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0f, 1.0f, 1.0f)],
                                    [NSValue valueWithCATransform3D:CATransform3DIdentity]];
            popAnimation.keyTimes = @[@0.2f, @0.5f, @0.75f, @1.0f];
            popAnimation.timingFunctions = @[[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut],
                                             [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut],
                                             [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
            [[UIApplication sharedApplication].keyWindow.rootViewController.view.layer addAnimation:popAnimation forKey:nil];
            AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
        });
        
    }
}

@end
